﻿PagesScripts.login = {};

PagesScripts.login.initHandlers = function() {
	if (!HTTPEvents.hasEventListener("onLogin")) {
		HTTPEvents.addEventListener("onLogin", PagesScripts.login.onLogin);
	}
	PagesScripts.login.drawLogin();
}

PagesScripts.login.checkLogin = function() {
    $.mobile.loading('show', {text: 'מתחבר למערכת הפורומים...'});
	if (!HTTPEvents.hasEventListener("onCheckLogin")) {
		HTTPEvents.addEventListener("onCheckLogin", PagesScripts.login.onCheckLogin);
	}	
	HTTPManager.CheckLogin();
}

PagesScripts.login.onCheckLogin = function(event) {
    $.mobile.loading('hide');
	if (event.data != null && event.data.success && event.data.success === true) {
		Config.setParam("username", event.data.username);
        PageManager.changePage("forums", {showLoadMsg: false});
	}
	else {
		Config.removeParam("username");
        PageManager.changePage("login", {showLoadMsg: false});
	}
}

PagesScripts.login.drawLogin = function(event) {
	if (Config.getParam("username") != null) {
		$("#loginBlock", $.mobile.activePage).hide();
		$("#logoutBlock", $.mobile.activePage).show();
		$("#loginUsername", $.mobile.activePage).html(Config.getParam("username"));
	}
}

PagesScripts.login.login = function() {
	PagesScripts.login.disableAllElements();
	HTTPManager.Login($("#login_username", $.mobile.activePage).val(), $("#login_password").val());
}

PagesScripts.login.onLogin = function(event) {
	if (event.data != null && event.data.success != null && event.data.success === true) {
		Config.setParam("username", $("#login_username", $.mobile.activePage).val());
		PageManager.changePage("../settings");
	}
	else {
		PagesScripts.login.enableAllElements();
		$("#loginError", $.mobile.activePage).show();
	}
}

PagesScripts.login.logout = function() {
	Config.removeParam("username");
	HTTPManager.Logout();
}

PagesScripts.login.disableAllElements = function() {
	$("#loginButton", $.mobile.activePage).addClass("ui-disabled");
	$("#loginError", $.mobile.activePage).hide();
	$("#loginProgress", $.mobile.activePage).show();
	$("#login_username", $.mobile.activePage).textinput("disable");
	$("#login_password", $.mobile.activePage).textinput("disable");
}

PagesScripts.login.enableAllElements = function() {
	$("#loginButton", $.mobile.activePage).removeClass("ui-disabled");
	$("#loginError", $.mobile.activePage).hide();
	$("#loginProgress", $.mobile.activePage).hide();
	$("#login_username", $.mobile.activePage).textinput("enable");
	$("#login_password", $.mobile.activePage).textinput("enable");
}

PagesScripts.login.hideAllElements = function() {
	$(".loginBlock", $.mobile.activePage).hide();
	$(".logoutBlock", $.mobile.activePage).show();
}

PagesScripts.login.showAllElements = function() {
	$(".loginBlock", $.mobile.activePage).show();
	$(".logoutBlock", $.mobile.activePage).hide();
	$("#loginError", $.mobile.activePage).hide();
	$("#loginProgress", $.mobile.activePage).hide();
}